package com.ykzb.talent.service.impl;

import com.ykzb.base.bean.ResultBean;
import com.ykzb.base.exception.BusinessException;
import com.ykzb.base.service.impl.BaseServiceImpl;
import com.ykzb.constants.Constants;
import com.ykzb.enums.MsgEnumType;
import com.ykzb.enums.SSDBKeys;
import com.ykzb.redis.RedisClient;
import com.ykzb.talent.dao.ITalentDao;
import com.ykzb.talent.model.Talent;
import com.ykzb.talent.service.ITalentService;
import com.ykzb.user.dao.IUserDao;
import com.ykzb.user.model.User;
import com.ykzb.user.service.UserService;
import com.ykzb.util.RSACoder;
import com.ykzb.util.RSAKey;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * Created by mac on 2017/4/7.
 */
@Service
public class TalentServiceImpl extends BaseServiceImpl implements ITalentService{

    @Autowired
    private RedisClient redisClient;


    @Autowired
    private IUserDao userDao;

    @Autowired
    private ITalentDao talentDao;

    /**
     * 成为专家
     * @param user
     * @throws Exception
     */
    @Override
    @Transactional
    public ResultBean registerTalent(HttpServletRequest request, String code, User user) throws Exception {
        ResultBean ret = new ResultBean();
        if (StringUtils.isNotBlank(code) && StringUtils.isNotEmpty(user.getPwd()) && StringUtils.isNumeric(user.getMobile())) {

            // 校验验证码
            String correctCode = redisClient.getJedis().get(SSDBKeys.mobile_code + user.getMobile());
            if (!code.equals(correctCode)) {
                ret.setSuccess(false);
                log.warn("resgister mobile:{} input error regCode:{}, correctCode:{}"+user.getMobile()+":"+code+":"+correctCode);
                throw new BusinessException(MsgEnumType.INVALID_REGISTER_CODE);
            }

            // 校验手机号
            boolean mobileExists = userDao.isMobileExists(user.getMobile());
            if (mobileExists) {
                ret.setSuccess(false);
                throw new BusinessException(MsgEnumType.REPEAT_REGISTER_MOBILE);
            }
            //模拟APP加密
            String pass = RSACoder.encryptByPublicKey2Base64(RSAKey.REGISTER_PUBLIC_KEY, user.getPwd());
            //解密
            String pass2 = RSACoder.decryptByPrivateKey4Base64(RSAKey.REGISTER_PRIVATE_KEY, pass);
            user.setPwd(pass2);
            user.setAvatarKey("");
            user.setAvatarKeyVersion(0);
            user.setSex(1);
            user.setRegisterType(1);
            user.setCreateTime(new Date());
            user.setModifyTime(new Date());
            user.setIsTalent(1);
            userDao.insert(user);
            //重新拿到注册用户
            User registerUser = userDao.selectUserByMobile(user.getMobile());
            //先检查访用户是否已经是人才，如果是则不会再插入
            Integer num = talentDao.selectTalentNumByUserId(registerUser.getUserId());
            if (num > 0){
                log.info("ID为"+registerUser.getUserId()+"用户已经在人才库，不再重复插入");
            }else{
                Talent talent = new Talent();
                talent.setUserId(registerUser.getUserId());
                talent.setName(registerUser.getNickname());
                talent.setResourceV(0);
                talent.setState(0);
                talent.setPostOffice("暂无");
                talent.setTalentClassId(0);
                talent.setCreateTime(new Date());
                talent.setUpdateTime(new Date());
                talentDao.insert(talent);
            }
            ret.setSuccess(true);
            //最后把用户追加到session中
            try {
                request.getSession().setAttribute(Constants.USER_SESSIOON_NAME,registerUser);
            }catch (Exception e){
                e.printStackTrace();
                log.info("共享用户SESSION："+registerUser.getUserId()+"到redis失败！");
            }
        }else{
            log.info("登录的手机号密码或验证码为空");
            ret.setSuccess(false);
            return ret;
        }
        return ret;
    }
}
